package rjeutsky.database.jpa.models;
import java.util.LinkedList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.Session;

import rjeutsky.models.User;

@Entity 
@Table(name = "User")
public class JPAUser  {
	
	private long id;
	private String login;
	private String password;
	private String salt;
	private List<JPASubscription> subscriptions;
	private List<JPAUserRole> roles;
	
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	public long getId() {
		return id;
	}
	
	public void setId(long id) {
		this.id = id;
	}
	
	public String getLogin() {
		return login;
	}
	
	public void setLogin(String login) {
		this.login = login;
	}
	
	public String getPassword() {
		return password;
	}
	
	public void setPassword(String password) {
		this.password = password;
	}
	
	public String getSalt() {
		return salt;
	}
	
	public void setSalt(String salt) {
		this.salt = salt;
	}
	
	@OneToMany(targetEntity=JPASubscription.class, mappedBy="user",
			cascade=CascadeType.ALL, fetch=FetchType.EAGER)
	public List<JPASubscription> getSubscriptions() {
		return subscriptions;
	}

	public void setSubscriptions(List<JPASubscription> subscriptions) {
		this.subscriptions = subscriptions;
	}
	
	@ManyToMany
	@JoinTable(name="UserUserRole", 
	joinColumns={@JoinColumn(name="userId")}, 
	inverseJoinColumns={@JoinColumn(name="userRoleId")})
	public List<JPAUserRole> getRoles() {
		return roles;
	}

	public void setRoles(List<JPAUserRole> roles) {
		this.roles = roles;
	}

	@Transient
	public User getUser() {
		User user = new User();
		user.setId(id);
		user.setLogin(login);
		user.setPassword(password);
		user.setSalt(salt);
		return user;
	}
	
	@Transient
	public static JPAUser getJPAUser(Session session, User user) {
		if (user == null) {
			return null;
		}
		
		return (JPAUser) session.get(JPAUser.class, user.getId());
	}
	
	@Transient
	public static List<User> getUsers(List<JPAUser> jpaUsers) {
		List<User> users = new LinkedList<User>();
		if (jpaUsers != null) {
			for (JPAUser user : jpaUsers) {
				users.add(user.getUser());
			}
		}
		
		return users;
	}
}
